package com.aboo.infrastructure.redis.frame.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Import;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.ReturnType;
import org.springframework.data.redis.core.StringRedisTemplate;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Slf4j
@Import({RedisUtils.class})
public class DistributedLockUtil {

    @Resource
    private StringRedisTemplate redisTemplateStr;

    /**
     * 尝试获取分布式锁
     *
     * @param lockKey    锁
     * @param requestId  请求标识
     * @param expireTime 超期时间
     * @return 是否获取成功
     */
    public boolean tryGetDistributedLock(String lockKey, String requestId, long expireTime) {
        boolean result = redisTemplateStr.opsForValue().setIfAbsent(lockKey, requestId, expireTime, TimeUnit.SECONDS);
        return result;
    }

    /**
     * 释放分布式锁
     *
     * @param lockKey   锁
     * @param requestId 请求标识
     * @return 是否释放成功
     */
    public boolean releaseDistributedLock(String lockKey, String requestId) {
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        Long result = redisTemplateStr.execute((RedisConnection connection) -> connection.eval(
                script.getBytes(),
                ReturnType.INTEGER,
                1,
                lockKey.getBytes(),
                requestId.getBytes()));

        if (Long.valueOf(1).equals(result)) {
            return true;
        }
        return false;
    }

}
